import { defineStore } from "pinia";
import { login, logout } from "@/api/login";
import { getToken, removeToken, setToken } from "@/utils/auth";
import { useAppStore } from "./app";
import { getInfo } from "@/api/admin/system/user";

interface LoginParams {
  user_name: string;
  password: string;
  captcha: string;
}

interface UserInfo {
  [key: string]: any;
}

interface UserStore {
  userInfo: UserInfo;
  token: string | undefined;
  roles: string[];
  permissions: string[];
}

export const useUserStore = defineStore({
  id: "user",
  state: (): UserStore => {
    return {
      userInfo: {},
      token: getToken(),
      roles: [],
      permissions: [],
    };
  },
  getters: {},
  actions: {
    // 登录
    async Login(params: LoginParams) {
      const res = await login(params);
      setToken(res.data.access_token);
      this.token = res.data.access_token;
      return res;
    },
    // 登出
    async Logout() {
      await logout();
      const appStore = useAppStore();
      appStore.resetTabs();
      removeToken();
      window.location.reload();
    },
    // 获取用户信息
    async GetInfo() {
      try {
        const res = await getInfo();
        if (res.data?.user?.roles && res.data.user?.roles.length > 0) {
          // 验证返回的roles是否是一个非空数组
          this.roles = res.data.roles;
          this.permissions = res.data.permissions;
        } else {
          if (res.data?.user?.id === 1) {
            this.permissions = ["*:*:*"];
          }
          this.roles = [];
        }
        this.userInfo = res.data.user;
        return res;
      } catch (error: any) {
        if (error.response.status === 401) {
          removeToken();
        }
      }
    },
  },
});
